package com.ujs.service.impl;

import com.ujs.dao.RoleDao;
import com.ujs.dao.UserInfoDao;
import com.ujs.pojo.Role;
import com.ujs.pojo.UserInfo;
import com.ujs.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @title: UserInfoServiceImpl
 * @Author liyunxiao
 * @Date: 2021/1/12 13:30
 */
@Service
public class UserInfoServiceImpl implements UserInfoService {

    @Autowired
    private UserInfoDao userInfoDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        UserInfo userInfo = userInfoDao.findByUserName(userName);
        User user = new User(userInfo.getUserName(), userInfo.getPassword(), userInfo.getStatus() == 0 ? false : true,
                true, true, true, getAuthority(userInfo.getRoles()));
        return user;
    }

    public List<SimpleGrantedAuthority>getAuthority(Set<Role> roles){
        List<SimpleGrantedAuthority>list=new ArrayList<>();
        for (Role role : roles) {
            list.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleName()));
        }
       return list;
    }

    @Override
    public List<UserInfo> findAll() {
        return userInfoDao.findAll();
    }

    @Override
    public void save(UserInfo userInfo) {
        String encode = bCryptPasswordEncoder.encode(userInfo.getPassword());//密码加密
        userInfo.setPassword(encode);
        userInfoDao.save(userInfo);
    }

    @Override
    public UserInfo findById(String userId) {
        return userInfoDao.getOne(userId);
    }

    @Override
    public List<Role> findOtherRoles(String userId) {
        //List<Role> otherRoles=new ArrayList<>();
        UserInfo userInfo = userInfoDao.getOne(userId);
        Set<Role> roles = userInfo.getRoles();
        List<Role> all = roleDao.findAll();
        for (Role role : roles) {
            if(all.contains(role)){
                all.remove(role);
            }
        }

        return all;
    }

    @Override
    public void addRoleToUser(String userId, String[] roleIds) {
        UserInfo userInfo = userInfoDao.getOne(userId);
        for (String roleId : roleIds) {
            Role role = roleDao.getOne(roleId);
            userInfo.getRoles().add(role);
        }
        userInfoDao.save(userInfo);
    }
}
